import 'package:flutter/services.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
import 'package:tender_flutter/constant/app_config.dart';

typedef Future<dynamic> JPushEventHandler(Map<String, dynamic> event);
typedef Future<dynamic> JPushRegistrationIDHandler(String regId);
typedef Future<dynamic> JPushPlatformVersionFailure(String message);

/// 极光推送
class JPushUtils {
  JPushUtils._internal();

  static JPush _jPush;

  static init() {
    if (_jPush == null) {
      _jPush = new JPush();
      _jPush.setBadge(0);
    }
  }

  static void stopPush() {
    _jPush.stopPush();
  }

  static void resumePush() {
    _jPush.resumePush();
  }

  static Future<void> addJpushEventHanlder(
      {JPushEventHandler onMyReceiveNotification,
      JPushEventHandler onMyOpenNotification,
      JPushEventHandler onMyReceiveMessage,
      JPushEventHandler onMyReceiveNotificationAuthorization,
      JPushRegistrationIDHandler onMyReceiveRegIdMessage,
      JPushPlatformVersionFailure onMyPlatformVersionFailure}) {
    try {
      _jPush.addEventHandler(
          onReceiveNotification: (Map<String, dynamic> message) async {
        print("flutter onReceiveNotification: $message");
        onMyReceiveNotification(message);
      }, onOpenNotification: (Map<String, dynamic> message) async {
        print("flutter onOpenNotification: $message");
        onMyOpenNotification(message);
      }, onReceiveMessage: (Map<String, dynamic> message) async {
        print("flutter onReceiveMessage: $message");
        onMyReceiveMessage(message);
      }, onReceiveNotificationAuthorization:
              (Map<String, dynamic> message) async {
        onMyReceiveNotificationAuthorization(message);
        print("flutter onReceiveNotificationAuthorization: $message");
      });
    } on PlatformException {
      onMyPlatformVersionFailure("Failed to get platform version.");
    }

    _jPush.setup(
      appKey: AppConfig.JVerification_key,
      channel: "devloper-default",
      production: true,
      debug: false,
    );
    _jPush.applyPushAuthority(
        new NotificationSettingsIOS(sound: true, alert: true, badge: true));

    // Platform messages may fail, so we use a try/catch PlatformException.
    _jPush.getRegistrationID().then((rid) {
      print("flutter get registration id : $rid");
      onMyReceiveRegIdMessage(rid);
    });
  }
}
